<template>
  <view class="attendance-container">
    <view class="attendance-header">
      <view class="date-info">
        <text class="date">{{ formatDate }}</text>
        <text class="week">{{ weekDay }}</text>
      </view>
      <view class="time-info">
        <text class="time">{{ currentTime }}</text>
      </view>
    </view>
    
    <view class="attendance-card">
      <view class="card-title">
        <text>今日打卡</text>
      </view>
      <view class="card-content">
        <view class="clock-item">
          <view class="clock-label">签到时间</view>
          <view class="clock-value">{{ todayStatus.clockInTime || '未签到' }}</view>
        </view>
        <view class="clock-item">
          <view class="clock-label">签退时间</view>
          <view class="clock-value">{{ todayStatus.clockOutTime || '未签退' }}</view>
        </view>
      </view>
      <view class="card-footer">
        <button 
          type="primary" 
          :disabled="false" 
          @click="handleClockClick"
        >
          {{ getButtonText }}
        </button>
      </view>
    </view>
    
    <!-- 补卡和请假按钮 -->
    <view class="action-card">
      <view class="action-buttons">
        <view class="action-button" @click="goToReapply">
          <uni-icons type="calendar" size="24" color="#3c9cff"></uni-icons>
          <text class="button-text">补卡申请</text>
        </view>
        <view class="action-button" @click="goToLeave">
          <uni-icons type="paperplane" size="24" color="#3c9cff"></uni-icons>
          <text class="button-text">请假申请</text>
        </view>
        <view class="action-button" @click="goToReapplyList">
          <uni-icons type="list" size="24" color="#3c9cff"></uni-icons>
          <text class="button-text">补卡记录</text>
        </view>
        <view class="action-button" @click="goToLeaveList">
          <uni-icons type="vip" size="24" color="#3c9cff"></uni-icons>
          <text class="button-text">请假记录</text>
        </view>
      </view>
    </view>
    
    <view class="attendance-list">
      <view class="list-title">
        <text>打卡记录</text>
        <text class="more" @tap="goToList">更多记录</text>
      </view>
      <view class="list-content">
        <view class="list-item" v-for="(item, index) in attendanceList" :key="index" @tap="goToDetail(item)">
          <view class="item-date">
            <text class="date">{{ formatListDate(item.attendanceDate) }}</text>
            <text class="week">{{ getWeekDay(item.attendanceDate) }}</text>
          </view>
          <view class="item-time">
            <view class="time-row">
              <text class="time-label">签到：</text>
              <text class="time-value">{{ item.clockInTime || '未签到' }}</text>
            </view>
            <view class="time-row">
              <text class="time-label">签退：</text>
              <text class="time-value">{{ item.clockOutTime || '未签退' }}</text>
            </view>
          </view>
          <view class="item-status" :class="getStatusClass(item)">
            {{ getStatusText(item) }}
          </view>
        </view>
        
        <uni-load-more :status="loadMoreStatus"></uni-load-more>
      </view>
    </view>
  </view>
</template>

<script>
import { getTodayStatus, listAttendance, clockIn, clockOut } from "@/api/system/attendance";

export default {
  name: "Attendance",
  data() {
    return {
      // 当前时间
      currentTime: '',
      // 定时器
      timer: null,
      // 今日打卡状态
      todayStatus: {
        clockInTime: '',
        clockOutTime: ''
      },
      // 打卡记录列表
      attendanceList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5
      },
      // 加载更多状态
      loadMoreStatus: 'more'
    };
  },
  computed: {
    formatDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    weekDay() {
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      return weekdays[new Date().getDay()];
    },
    getButtonText() {
      if (this.todayStatus.clockInTime && this.todayStatus.clockOutTime) {
        return '今日已完成';
      } else if (this.todayStatus.clockInTime && !this.todayStatus.clockOutTime) {
        return '签退';
      } else {
        return '签到';
      }
    }
  },
  created() {
    this.updateTime();
    this.timer = setInterval(this.updateTime, 1000);
    
    // 先初始化本地状态
    this.todayStatus = {
      clockInTime: '',
      clockOutTime: ''
    };
    
    // 获取后端数据，但不覆盖本地状态
    this.getTodayAttendanceStatus().catch(err => {
      console.error('初始化失败:', err);
    });
    
    // 获取打卡记录
    this.getList();
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    // 更新当前时间
    updateTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      const seconds = now.getSeconds().toString().padStart(2, '0');
      this.currentTime = `${hours}:${minutes}:${seconds}`;
    },
    
    // 获取格式化的当前时间
    getCurrentFormattedTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      const seconds = now.getSeconds().toString().padStart(2, '0');
      return `${hours}:${minutes}:${seconds}`;
    },
    
    // 获取今日打卡状态
    getTodayAttendanceStatus() {
      return new Promise((resolve, reject) => {
        // 获取当前用户ID
        const currentUserId = this.$store.getters.id;
        console.log('获取今日状态 - 当前用户ID:', currentUserId);
        
        getTodayStatus(currentUserId).then(res => {
          if (res.code === 200) {
            console.log('获取今日打卡状态成功:', res.data);
            
            // 确保返回的数据是当前用户的
            const data = res.data || {
              clockInTime: '',
              clockOutTime: '',
              userId: currentUserId
            };
            
            // 验证返回的用户ID是否匹配当前用户
            if (data.userId && data.userId != currentUserId) {
              console.error('返回的打卡记录不属于当前用户, 记录用户ID:', data.userId, '当前用户ID:', currentUserId);
              this.todayStatus = {
                clockInTime: '',
                clockOutTime: ''
              };
              resolve(this.todayStatus);
              return;
            }
            
            // 如果本地已有签到/签退数据但服务器没有，则保留本地数据
            const newStatus = JSON.parse(JSON.stringify(data));
            if (this.todayStatus && this.todayStatus.clockInTime && !newStatus.clockInTime) {
              console.log('保留本地签到时间:', this.todayStatus.clockInTime);
              newStatus.clockInTime = this.todayStatus.clockInTime;
            }
            if (this.todayStatus && this.todayStatus.clockOutTime && !newStatus.clockOutTime) {
              console.log('保留本地签退时间:', this.todayStatus.clockOutTime);
              newStatus.clockOutTime = this.todayStatus.clockOutTime;
            }
            
            this.todayStatus = newStatus;
            resolve(this.todayStatus);
          } else {
            console.error('获取今日打卡状态失败:', res.msg);
            reject(res.msg);
          }
        }).catch(error => {
          console.error('获取今日打卡状态请求失败:', error);
          // 初始化默认状态，但不覆盖已有的本地状态
          if (!this.todayStatus || (!this.todayStatus.clockInTime && !this.todayStatus.clockOutTime)) {
            this.todayStatus = {
              clockInTime: '',
              clockOutTime: ''
            };
          }
          reject(error);
        });
      });
    },
    // 查询打卡记录列表
    getList() {
      this.loadMoreStatus = 'loading';
      // 确保查询参数包含当前用户ID
      const currentUserId = this.$store.getters.id;
      console.log('当前用户ID:', currentUserId);
      
      this.queryParams = {
        ...this.queryParams,
        userId: currentUserId // 添加当前用户ID
      };
      
      console.log('查询参数:', JSON.stringify(this.queryParams));
      
      listAttendance(this.queryParams).then(response => {
        if (response && response.rows) {
          this.attendanceList = response.rows;
          this.loadMoreStatus = this.attendanceList.length >= response.total ? 'noMore' : 'more';
          
          // 检查并更新今日状态
          const today = this.formatDate;
          const todayRecord = this.attendanceList.find(item => {
            return item.attendanceDate && item.attendanceDate.includes(today.split('-').slice(0, 3).join('-'));
          });
          
          if (todayRecord) {
            console.log('列表中找到今日记录:', todayRecord);
            // 更新本地状态，但保留已有的值
            const updatedStatus = {
              clockInTime: todayRecord.clockInTime || this.todayStatus.clockInTime || '',
              clockOutTime: todayRecord.clockOutTime || this.todayStatus.clockOutTime || ''
            };
            
            console.log('从列表更新本地状态:', updatedStatus);
            this.todayStatus = updatedStatus;
          }
        } else {
          console.error('获取打卡记录列表失败:', response);
          this.loadMoreStatus = 'noMore';
          this.attendanceList = [];
        }
      }).catch(error => {
        console.error('获取打卡记录列表请求失败:', error);
        this.loadMoreStatus = 'noMore';
        this.attendanceList = [];
      });
    },
    // 处理按钮点击事件
    handleClockClick() {
      console.log('handleClockClick 被触发');
      if (this.todayStatus.clockInTime && !this.todayStatus.clockOutTime) {
        this.handleClock('out');
      } else if (!this.todayStatus.clockInTime) {
        this.handleClock('in');
      } else {
        uni.showToast({
          title: '今日打卡已完成',
          icon: 'none'
        });
      }
    },
    
    // 处理打卡操作
    handleClock(type) {
      console.log('handleClock 被触发, type:', type);
      
      // 验证是否可以进行操作
      if (type === 'out' && !this.todayStatus.clockInTime) {
        uni.showToast({
          title: '请先进行签到',
          icon: 'none'
        });
        return;
      }
      
      // 准备请求数据
      let data = {};
      
      // 对于签到操作，只需要基本信息
      if (type === 'in') {
        data = {
          clockInLocation: '公司',
          remark: ''
        };
      } 
      // 对于签退操作，需要attendanceId和位置信息
      else if (type === 'out') {
        // 先刷新今日状态
        this.getTodayAttendanceStatus().then(() => {
          if (!this.attendanceList || this.attendanceList.length === 0) {
            console.error('签退失败：打卡记录列表为空');
            uni.showToast({
              title: '无法获取签到记录，请刷新页面',
              icon: 'none'
            });
            return;
          }
          
          // 查找今天的打卡记录
          const today = this.formatDate;
          console.log('查找今日打卡记录，当前日期:', today);
          
          const todayRecord = this.attendanceList.find(item => {
            const match = item.attendanceDate && item.attendanceDate.includes(today.split('-').slice(0, 3).join('-'));
            if (match) {
              console.log('找到匹配记录:', JSON.stringify(item));
            }
            return match;
          });
          
          if (!todayRecord) {
            console.error('未找到今日打卡记录');
            uni.showToast({
              title: '未找到签到记录，请先签到',
              icon: 'none'
            });
            return;
          }
          
          if (!todayRecord.attendanceId) {
            console.error('打卡记录缺少ID:', todayRecord);
            uni.showToast({
              title: '签到记录异常，请联系管理员',
              icon: 'none'
            });
            return;
          }
          
          // 构建签退数据
          data = {
            attendanceId: todayRecord.attendanceId,  // 使用原始的attendanceId
            clockOutLocation: '公司',
            remark: ''
          };
          
          console.log('准备签退数据:', JSON.stringify(data));
          
          // 执行签退请求
          this.executeClockOperation(type, data);
        }).catch(error => {
          console.error('获取今日状态失败:', error);
          uni.showToast({
            title: '获取签到状态失败，请重试',
            icon: 'none'
          });
        });
        return; // 提前返回，避免执行后续代码
      }
      
      // 执行签到请求
      if (type === 'in') {
        this.executeClockOperation(type, data);
      }
    },
    
    // 执行打卡操作
    executeClockOperation(type, data) {
      const clockFunc = type === 'in' ? clockIn : clockOut;
      console.log('准备调用API:', type === 'in' ? 'clockIn' : 'clockOut', '参数:', JSON.stringify(data));
      
      uni.showLoading({
        title: type === 'in' ? "签到中" : "签退中"
      });
      
      // 立即获取当前时间，确保UI和请求使用相同的时间
      const currentTime = this.getCurrentFormattedTime();
      
      // 调用API，等待真实响应
      clockFunc(data).then(res => {
        console.log('API返回结果:', JSON.stringify(res));
        uni.hideLoading();
        
        if (res.code === 200) {
          console.log('设置当前时间:', currentTime, '类型:', type);
          
          // 保存当前状态的副本
          const updatedStatus = JSON.parse(JSON.stringify(this.todayStatus));
          
          if (type === 'in') {
            updatedStatus.clockInTime = currentTime;
          } else if (type === 'out') {
            updatedStatus.clockOutTime = currentTime;
            this.updateAttendanceListItem(currentTime);
          }
          
          // 更新状态
          this.todayStatus = updatedStatus;
          
          uni.showToast({
            title: type === 'in' ? "签到成功" : "签退成功",
            icon: "success"
          });
          
          // 刷新数据
          setTimeout(() => {
            console.log('延时刷新数据');
            this.getTodayAttendanceStatus();
            this.getList();
          }, 1000);
        } else {
          console.error('API返回错误:', res.msg);
          uni.showToast({
            title: res.msg || (type === 'in' ? '签到失败' : '签退失败'),
            icon: 'none',
            duration: 2000
          });
        }
      }).catch((error) => {
        console.error('API调用失败:', error);
        uni.hideLoading();
        
        uni.showToast({
          title: type === 'in' ? '签到请求失败' : '签退请求失败',
          icon: 'none',
          duration: 2000
        });
      });
    },
    
    // 更新列表中的签退时间
    updateAttendanceListItem(clockOutTime) {
      if (!this.attendanceList || this.attendanceList.length === 0) {
        return;
      }
      
      const today = this.formatDate;
      const index = this.attendanceList.findIndex(item => {
        return item.attendanceDate && item.attendanceDate.includes(today.split('-').slice(0, 3).join('-'));
      });
      
      if (index !== -1) {
        // 创建新数组以触发视图更新
        const newList = [...this.attendanceList];
        newList[index] = {
          ...newList[index],
          clockOutTime: clockOutTime
        };
        console.log('手动更新列表中的签退状态:', newList[index]);
        this.attendanceList = newList;
        
        // 同时更新本地状态
        if (this.todayStatus) {
          this.todayStatus = {
            ...this.todayStatus,
            clockOutTime: clockOutTime
          };
          console.log('更新本地签退状态:', this.todayStatus);
        }
      }
    },
    // 格式化列表日期
    formatListDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${month}-${day}`;
    },
    // 获取星期几
    getWeekDay(dateStr) {
      if (!dateStr) return '';
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      return weekdays[new Date(dateStr).getDay()];
    },
    // 获取状态样式类
    getStatusClass(item) {
      if (!item.clockInTime) return 'status-absent';
      if (!item.clockOutTime) return 'status-incomplete';
      return 'status-normal';
    },
    // 获取状态文本
    getStatusText(item) {
      if (!item.clockInTime) return '缺勤';
      if (!item.clockOutTime) return '未签退';
      return '正常';
    },
    // 跳转到详情页
    goToDetail(item) {
      this.$tab.navigateTo(`/pages/system/attendance/detail?id=${item.attendanceId}`);
    },
    // 跳转到列表页
    goToList() {
      this.$tab.navigateTo('/pages/system/attendance/list');
    },
    // 跳转到补卡申请页
    goToReapply() {
      this.$tab.navigateTo('/pages/system/attendance/reapply');
    },
    // 跳转到请假申请页
    goToLeave() {
      this.$tab.navigateTo('/pages/system/attendance/leave');
    },
    // 跳转到补卡记录页
    goToReapplyList() {
      this.$tab.navigateTo('/pages/system/attendance/reapply-list');
    },
    // 跳转到请假记录页
    goToLeaveList() {
      this.$tab.navigateTo('/pages/system/attendance/leave-list');
    }
  }
};
</script>

<style lang="scss" scoped>
.attendance-container {
  padding: 15px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.attendance-header {
  background-color: #3c9cff;
  border-radius: 10px;
  padding: 20px;
  color: #fff;
  margin-bottom: 15px;
  box-shadow: 0 2px 10px rgba(60, 156, 255, 0.3);
  
  .date-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    
    .date {
      font-size: 18px;
      font-weight: bold;
    }
    
    .week {
      font-size: 16px;
    }
  }
  
  .time-info {
    .time {
      font-size: 36px;
      font-weight: bold;
    }
  }
}

.attendance-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  
  .card-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }
  
  .card-content {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
    
    .clock-item {
      text-align: center;
      flex: 1;
      
      .clock-label {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }
      
      .clock-value {
        font-size: 18px;
        font-weight: bold;
      }
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: center;
    
    button {
      width: 80%;
      height: 45px;
      font-size: 16px;
    }
  }
}

.action-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  
  .action-buttons {
    display: flex;
    justify-content: space-around;
    
    .action-button {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      
      .button-text {
        font-size: 14px;
        color: #666;
        margin-top: 5px;
      }
    }
  }
}

.attendance-list {
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  
  .list-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
    
    .more {
      font-size: 14px;
      color: #3c9cff;
      font-weight: normal;
    }
  }
  
  .list-content {
    .list-item {
      display: flex;
      align-items: center;
      padding: 15px 0;
      border-bottom: 1px solid #eee;
      
      &:last-child {
        border-bottom: none;
      }
      
      .item-date {
        width: 60px;
        text-align: center;
        
        .date {
          font-size: 16px;
          font-weight: bold;
          display: block;
        }
        
        .week {
          font-size: 12px;
          color: #666;
        }
      }
      
      .item-time {
        flex: 1;
        padding: 0 15px;
        
        .time-row {
          display: flex;
          margin-bottom: 5px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .time-label {
            width: 50px;
            color: #666;
          }
          
          .time-value {
            font-weight: bold;
          }
        }
      }
      
      .item-status {
        width: 60px;
        height: 25px;
        line-height: 25px;
        text-align: center;
        border-radius: 12.5px;
        font-size: 12px;
        
        &.status-normal {
          background-color: #e1f3d8;
          color: #67c23a;
        }
        
        &.status-incomplete {
          background-color: #fdf6ec;
          color: #e6a23c;
        }
        
        &.status-absent {
          background-color: #fde2e2;
          color: #f56c6c;
        }
      }
    }
  }
}
</style> 